﻿<?php

class BilletincidentController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update','traiter'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->layout='//layouts/column1';
		
		$model=$this->loadModel($id);
		
		$poste=POSTE::model()->findByPk($model->ID_POSTE);
		$nPoste=$poste->NUM_SERIE;
		
		$pbLog=PROBLEMELOGICIEL::model()->findByPk($model->ID_PROBLEME_LOGICIEL);
		
		if(!empty($pbLog))
			$nProbleme=$pbLog->LIBELLE_PROBLEME_LOGICIEL;
		else
		{
			$pbMat=PROBLEMEMATERIEL::model()->findByPk($model->ID_PROBLEME_MATERIEL);	
			$nProbleme=$pbMat->LIBELLE_PROBLEME_MATERIEL;
		}
		
		$Emetteur=EMETTEUR::model()->findByPk($model->ID_EMETTEUR);
		$nEmetteur=$Emetteur->NOM_EMETTEUR;
		
		if($model->RESOLU == 0)
			$etat = 'Ouvert';
		else
			$etat = 'Fermé';
		
		$this->render('view',array(
			'model'=>$this->loadModel($id),
			'role'=>Yii::app()->user->getState('role'),
			'nPoste'=>$nPoste,
			'nProbleme'=>$nProbleme,
			'nEmetteur'=>$nEmetteur,
			'etat'=>$etat,
		));
		
		$this->layout='//layouts/column2';
	}
	
	public function actionClore($id)
	{
	
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model = new BILLETINCIDENT;
		
		//recupération des postes pour la liste déroulante
		$allPoste = new POSTE;
		$poste = $allPoste->findAll();
		$poste = CHtml::listData($poste,'ID_POSTE', 'NUM_SERIE');
		
		//recupération des problème logiciels pour la liste déroulante
		$allPbLog = new PROBLEMELOGICIEL;
		$pbLog = $allPbLog->findAll();
		$pbLog = CHtml::listData($pbLog,'ID_PROBLEME_LOGICIEL', 'LIBELLE_PROBLEME_LOGICIEL');
		
		//recupération des problèmes materiels pour la liste déroulante
		$allPbMat = new PROBLEMEMATERIEL;
		$pbMat = $allPbMat->findAll();
		$pbMat = CHtml::listData($pbMat,'ID_PROBLEME_MATERIEL', 'LIBELLE_PROBLEME_MATERIEL');
				
		//recupération des materiels pour la liste déroulante
		$allMat = new MATERIEL;
		$mat = $allMat->findAll();
		$mat = CHtml::listData($mat,'ID_MATERIEL', 'NOM_MATERIEL');
		
		//recupération des logiciels pour la liste déroulante
		$allLog = new LOGICIEL;
		$log = $allLog->findAll();
		$log = CHtml::listData($log,'ID_LOGICIEL', 'NOM_LOGICIEL');
				
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['BILLETINCIDENT']))
		{
			if(isset($_FILES['BILLETINCIDENT']['name']['PIECE_JOINTE']) && $_FILES['BILLETINCIDENT']['name']['PIECE_JOINTE'] != '')
			{
				$connection=Yii::app()->db;
				$command=$connection->createCommand("SELECT MAX(ID_BILLET_INCIDENT) FROM BILLET_INCIDENT");
				$id=$command->queryRow();
				move_uploaded_file($_FILES['BILLETINCIDENT']['tmp_name']['PIECE_JOINTE'], "pieceJointe/".($id['MAX(ID_BILLET_INCIDENT)']+ 1).'_'.$_FILES['BILLETINCIDENT']['name']['PIECE_JOINTE']);  
			}
			$utilisateur=Emetteur::model()->findByAttributes(array('LOGIN_EMETTEUR'=>Yii::app()->user->name));
			
			$_POST['BILLETINCIDENT']['ID_POSTE'] = $_POST['poste'];
			if($_POST['probleme'] == 0)
			{
				$_POST['BILLETINCIDENT']['ID_PROBLEME_LOGICIEL'] = $_POST['pbLog'];
				$_POST['BILLETINCIDENT']['ID_LOGICIEL'] = $_POST['log'];
			}
			elseif($_POST['probleme'] == 1)
			{
				$_POST['BILLETINCIDENT']['ID_PROBLEME_MATERIEL'] = $_POST['pbMat'];
				$_POST['BILLETINCIDENT']['ID_MATERIEL'] = $_POST['mat'];
			}
			
			$d = new DateTime();
			$nb = 1;
			if($_POST['urgence'] == 'Non prioritaire')
				$nb = 5;
			elseif($_POST['urgence'] == 'Normal')
				$nb = 3;
			else
				$nb = 1;
			$dateFin= $d->setTimestamp(mktime(0, 0, 0, date("m")  , date("d") + $nb, date("Y")));
			$_POST['BILLETINCIDENT']['DATE_FIN_PREVUE'] = $dateFin->format("d-m-Y");
			
			$_POST['BILLETINCIDENT']['URGENCE'] = $_POST['urgence'];
			$_POST['BILLETINCIDENT']['DATE_OUVERTURE'] = date("d-m-Y");
			$_POST['BILLETINCIDENT']['ID_EMETTEUR'] = $utilisateur['ID_EMETTEUR'];
			$_POST['BILLETINCIDENT']['RESOLU'] = 0;
		
			$model->attributes=$_POST['BILLETINCIDENT'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->ID_BILLET_INCIDENT));
		}
		$this->render('create',array(
			'model'=>$model,
			'poste'=>$poste,
			'pbLog'=>$pbLog,
			'pbMat'=>$pbMat,
			'mat'=>$mat,
			'log'=>$log
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['BILLETINCIDENT']))
		{
			$model->attributes=$_POST['BILLETINCIDENT'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->ID_BILLET_INCIDENT));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		
		$allPoste = new POSTE;
		$poste = $allPoste->findAll();
		//recupération des emetteurs
		$allEmetteur = new EMETTEUR;
		$emetteur = $allEmetteur->findAll();
		
		$this->layout='//layouts/column1';
		if(Yii::app()->user->getState('role') == 2)
		{
			$utilisateur=Emetteur::model()->findByAttributes(array('LOGIN_EMETTEUR'=>Yii::app()->user->name));
			$dataProvider= new CActiveDataProvider('BILLETINCIDENT' ,array('criteria'=>array('condition'=>'ID_EMETTEUR='.$utilisateur['ID_EMETTEUR'])));
		}
		else
			$dataProvider=new CActiveDataProvider('BILLETINCIDENT');

		$i=0;
		foreach($dataProvider->getData() as $record) {
			if($record->RESOLU == 0)
				$dataProvider->getData()[$i]->RESOLU = 'Ouvert';
			else
				$dataProvider->getData()[$i]->RESOLU = 'Fermé';
				
			 // $data= Affectation::model()->findByAttributes(array(''=>$dataProvider->getData()[$i]->ID_BILLET_INCIDENT;
			
				//A FINIR
			
			 // $dataProvider->getData()[$i]->OPERATEUR = ;
			
			$i++;
		}
			
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
			'role'=>Yii::app()->user->getState('role'),
			'emetteur'=>$emetteur,
		));
	}
	
	public function actionTraiter()
	{
		//recupération des emetteurs
		$allEmetteur = new EMETTEUR;
		$emetteur = $allEmetteur->findAll();
		$this->layout='//layouts/column1';
		$dataProvider=new CActiveDataProvider('BILLETINCIDENT');
		$this->render('traiter',array(
				'dataProvider'=>$dataProvider,
				'emetteur'=>$emetteur,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new BILLETINCIDENT('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['BILLETINCIDENT']))
			$model->attributes=$_GET['BILLETINCIDENT'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return BILLETINCIDENT the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=BILLETINCIDENT::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param BILLETINCIDENT $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='billetincident-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
